package cn.gaotu.basic.interceptor;

import cn.gaotu.basic.anno.PreAuthorize;
import cn.gaotu.basic.jwt.JwtUtils;
import cn.gaotu.basic.jwt.LoginResult;
import cn.gaotu.basic.jwt.Payload;
import cn.gaotu.basic.jwt.RsaUtils;
import cn.gaotu.system.mapper.PermissionMapper;
import cn.gaotu.user.domain.Logininfo;
import cn.gaotu.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.gaotu.basic.jwt.JwtUtils.getInfoFromToken;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("U-TOKEN");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (StringUtils.hasLength(token)) {
            //根据token从redis中获取登录信息
//            Object logTemp = redisTemplate.opsForValue().get(token);
            //现在我们需要解密JWT串等到登录人和登录的对应权限
            //获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            //使用公钥进行解密
            Payload<LoginResult> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginResult.class);
            LoginResult loginResult = payload.getUserInfo();
            if (loginResult != null) {
                //增加权限校验===即 登录之后,也需要看对应的用户是否有权限进行查询操作
                //1.区分是否是员工,是就需要校验权限
                Logininfo logininfo = loginResult.getLogininfo();
                if (logininfo.getType() == 1) {//代表是员工,需要校验权限
                    //得到当前请求的资源
                    HandlerMethod method = (HandlerMethod) handler;
                    PreAuthorize methodAnnotation = method.getMethodAnnotation(PreAuthorize.class);
                    if (methodAnnotation != null) {
                        String value = methodAnnotation.value();//本次请求的sn
                        //查询出当前登录人拥有的权限的资源 permissions
                        //List<String> perMissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
                        //判断permission是否包含url
                        if (!loginResult.getPermissions().contains(value)) {
                            //不包含提示权限不足
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }
                //刷新过期时间
                redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
                return true;
            }
        }
        //验证不通过,设置跳转登录
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;
    }
}